package com.ljw.test;

import android.app.Application;
import android.database.sqlite.SQLiteDatabase;

import com.ljw.test.dao.DaoMaster;
import com.ljw.test.dao.DaoSession;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyApplication extends Application {
    private static MyApplication application;

    private SQLiteDatabase db;

    private DaoSession mDaoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        setDatabase();
    }

    public static MyApplication getApplication() {
        return application;
    }

    /**
     * 进行greenDao的初始化
     */
    private void setDatabase() {
        copyDbFile();
        DaoMaster.DevOpenHelper mHelper = new DaoMaster.DevOpenHelper(this, "candidate.db", null);
        db = mHelper.getWritableDatabase();
        DaoMaster mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    public SQLiteDatabase getDb() {
        return db;
    }

    private void copyDbFile() {
        InputStream in = null;
        FileOutputStream out = null;

        String path = "/data/data/" + getPackageName() + "/databases/";
        File file = new File(path + "candidate.db");

        File filePath = new File(path);

        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        if (file.exists()) return;

        try {
            in = getAssets().open("candidate.db"); // 从assets目录下复制
            System.out.println("open");
            out = new FileOutputStream(file);
            int length = -1;
            byte[] buf = new byte[1024];
            while ((length = in.read(buf)) != -1) {
                out.write(buf, 0, length);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) in.close();
                if (out != null) out.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}
